package de.tayrracer.geoobjects;

import java.awt.Color;

import de.tayrracer.Math;

public class Sphere extends BaseObject {
	private double radius;
	
	public Sphere (double[] position, double radius)
	{
		this.position = position;
		this.radius = radius;
	}
	
	private double[] isCut(double[] origin, double[] direction){
		double[] difference = Math.subtractVectors(origin,position);
		double scalarDir = Math.scalarProduct(direction,direction);
		double scalarDif = Math.scalarProduct(difference,difference);
		double scalarDirDif = Math.scalarProduct(direction,difference);
		if (scalarDirDif*scalarDirDif>=scalarDir*(scalarDif-radius*radius)){
			double result1 = -scalarDirDif/scalarDir+java.lang.Math.sqrt((scalarDirDif*scalarDirDif)/(scalarDir*scalarDir)-(scalarDif-radius*radius)/(scalarDir));
			double result2 = -scalarDirDif/scalarDir-java.lang.Math.sqrt((scalarDirDif*scalarDirDif)/(scalarDir*scalarDir)-(scalarDif-radius*radius)/(scalarDir));
			if (result1<0){
				if (result2<0)
					return null;
				return Math.addVectors(origin, Math.scalarMult(result2,direction));
			}
			if (result2<0)
				return Math.addVectors(origin, Math.scalarMult(result1,direction));
			if (result1>result2)
				return Math.addVectors(origin, Math.scalarMult(result2,direction));
			return Math.addVectors(origin, Math.scalarMult(result1,direction));
		}
		return null;
	}
	
	public Ray getColorForCut(double[] origin, double[] direction, BaseObject[] objects, int count){
		double[] cutPoint = isCut(origin,direction);
		if (cutPoint!= null){
			Ray result = new Ray();
			result.position = cutPoint;
			if (mirrorPercentage == 0 || count <= 0){
				result.rayColor = objectColor;
				return result;
			}
			Color theColor = Color.BLACK;
			double distance  = Double.POSITIVE_INFINITY;
			float[] rgbArr;
			theColor = de.tayrracer.PictureDrawer.getFirstCut(objects, cutPoint, direction, distance);
			int[] tempRGB = new int[3];
			tempRGB[0]=java.lang.Math.round((float)(mirrorPercentage*theColor.getRed()+(1-mirrorPercentage)*objectColor.getRed()));
			tempRGB[1]=java.lang.Math.round((float)(mirrorPercentage*theColor.getGreen()+(1-mirrorPercentage)*objectColor.getGreen()));
			tempRGB[2]=java.lang.Math.round((float)(mirrorPercentage*theColor.getBlue()+(1-mirrorPercentage)*objectColor.getBlue()));
			rgbArr = Color.RGBtoHSB(tempRGB[0], tempRGB[1], tempRGB[2], null);
			result.rayColor = Color.getHSBColor(rgbArr[0], rgbArr[1], rgbArr[2]);
			return result;
		}
		return null;
	}
}
